<template>
  <div>
    <el-button type="warning" @click="open">导入样品</el-button>

    <el-dialog v-model="openDia" title="样品导入" width="1000px" style="height:800px">

      <el-upload
          ref="upload"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :show-file-list="false"
          style="margin-bottom: 10px"
          accept=".xls,.xlsx"
          @change="handleChange"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
      </el-upload>
      <el-button type="warning" plain style="position: absolute;right: 30px;top:55px" @click="downloadTemplate">下载模板</el-button>
      <el-table :data="samples"
                style="width: 100%"
                height="550px"
                border
                default-expand-all>
        <el-table-column fixed label="序号"  width=100 type="index" align="center" prop="sampleId" />
        <el-table-column label="样品编号" align="center" prop="sampleName" width="200">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].sampleName">{{scope.row.sampleName}}</span>
            <span v-else style="color: green">{{scope.row.sampleName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次/取样时间" align="center" prop="batch" width="200">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].batch">{{scope.row.batch}}</span>
            <span v-else style="color: green">{{scope.row.batch}}</span>
          </template>
        </el-table-column>
        <el-table-column label="井号" align="center" prop="wellId">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].wellId">{{scope.row.wellId}}</span>
            <span v-else style="color: green">{{scope.row.wellId}}</span>
          </template>
        </el-table-column>
        <el-table-column label="深度(m)" align="center" prop="depth">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].depth">{{scope.row.depth}}</span>
            <span v-else style="color: green">{{scope.row.depth}}</span>
          </template>
        </el-table-column>
        <el-table-column label="岩石类型" align="center" prop="rockType" width="150">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].rockType">{{scope.row.rockType}}</span>
            <span v-else style="color: green">{{scope.row.rockType}}</span>
          </template>
        </el-table-column>
        <el-table-column label="样品量(g)" align="center" prop="sampleQuantity">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].sampleQuantity">{{scope.row.sampleQuantity}}</span>
            <span v-else style="color: green">{{scope.row.sampleQuantity}}</span>
          </template>
        </el-table-column>
        <el-table-column label="样品尺寸(cm)" align="center" prop="sampleSize" width="120">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].sampleSize">{{scope.row.sampleSize}}</span>
            <span v-else style="color: green">{{scope.row.sampleSize}}</span>
          </template>
        </el-table-column>
        <el-table-column label="送样人" align="center" prop="sampleSender">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].sampleSender">{{scope.row.sampleSender}}</span>
            <span v-else style="color: green">{{scope.row.sampleSender}}</span>
          </template>
        </el-table-column>
        <el-table-column label="送样形式" align="center" prop="sendingStyle" width="120">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].sendingStyle">{{scope.row.sendingStyle}}</span>
            <span v-else style="color: green">{{scope.row.sendingStyle}}</span>
          </template>
        </el-table-column>
        <el-table-column label="送样日期" align="center" prop="deliveryDate" width="180">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].deliveryDate">{{scope.row.deliveryDate}}</span>
            <span v-else style="color: green">{{scope.row.deliveryDate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" prop="senderPhone" width="180">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].senderPhone">{{scope.row.senderPhone}}</span>
            <span v-else style="color: green">{{scope.row.senderPhone}}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="linkman" width="200">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].linkman">{{scope.row.linkman}}</span>
            <span v-else style="color: green">{{scope.row.linkman}}</span>
          </template>
        </el-table-column>
        <el-table-column label="样品备注" align="center" prop="sampleBackup" width="200">
          <template #default="scope">
            <span v-if="!updates[scope.row.__rowNum__-2].sampleBackup">{{scope.row.sampleBackup}}</span>
            <span v-else style="color: green">{{scope.row.sampleBackup}}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-button text type="primary" @click="changeSample(scope.row.__rowNum__)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button @click="handleImport"
          type="success" style="margin-left: 45%;margin-top: 20px;font-size: 18px" size="large">导 入</el-button>
    </el-dialog>

    <el-dialog v-model="openChange"
               title="样品修改" width="800px" append-to-body
               style=" border-radius: 20px;padding-right: 10px;padding-left: 10px" class="larger-input">
      <el-form ref="sampleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="样品编号" prop="sampleName">
          <el-input v-model="form.sampleName" placeholder="请输入样品编号"/>
        </el-form-item>
        <el-form-item label="岩石类型" prop="rockType">
          <el-input v-model="form.rockType" placeholder="请输入岩石类型"/>
        </el-form-item>
        <el-form-item label="井号" prop="wellId">
          <el-input v-model="form.wellId" placeholder="请输入井号"/>
        </el-form-item>
        <el-form-item label="深度(m)" prop="depth">
          <el-input v-model="form.depth" placeholder="请输入深度(m)"/>
        </el-form-item>
        <el-form-item label="样品量(g)" prop="sampleQuantity">
          <el-input v-model="form.sampleQuantity" placeholder="请输入样品量(g)"/>
        </el-form-item>
        <el-form-item label="样品尺寸(cm)" prop="sampleSize">
          <el-input v-model="form.sampleSize" placeholder="请输入样品尺寸(cm)"/>
        </el-form-item>
        <el-form-item label="样品备注" prop="sampleBackup">
          <el-input v-model="form.sampleBackup" placeholder="请输入样品备注"/>
        </el-form-item>
        <el-form-item label="送样人" prop="sampleSender">
          <el-input v-model="form.sampleSender" placeholder="请输入送样人"/>
        </el-form-item>
        <el-form-item label="送样形式" prop="sendingStyle">
          <el-select
              v-model="form.sendingStyle"
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入送样形式"
              style="width: 800px"
          >
            <el-option key="1" label="快递" value="快递"/>
            <el-option key="2" label="人工" value="人工"/>
            <el-option key="3" label="其他" value="其他"/>
          </el-select>
        </el-form-item>
        <el-form-item label="送样日期" prop="deliveryDate">
          <el-date-picker clearable
                          v-model="form.deliveryDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择送样日期"
                          style="width: 800px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="senderPhone">
          <el-input v-model="form.senderPhone" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="批次/取样时间" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次/取样时间"/>
        </el-form-item>
        <el-form-item label="联系人" prop="linkman">
          <el-input v-model="form.linkman" placeholder="请输入联系人"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import * as xlsx from 'xlsx'
import {ElNotification, genFileId} from "element-plus";
import {importSamples} from "@/api/sample/sample.js";

const props=defineProps(['projectId']);
const emit=defineEmits(['refresh'])
const pid=props.projectId;

const openDia=ref(false);

function open(){
  openDia.value=true
}


const upload=ref();
const samples=ref([]);
const updates=ref([]);

//样品修改
const openChange=ref(false);
const form=ref({projectId: pid});
const rules=ref({
  sampleName: [
    {required: true, message: "样品名不能为空", trigger: "blur"}
  ],
  sampleQuantity: [
    {required: true, message: "样品量不能为空", trigger: "blur"}
  ],
  sampleSender: [
    {required: true, message: "送样人不能为空", trigger: "blur"}
  ],
  sendingStyle: [
    {required: true, message: "送样形式不能为空", trigger: "blur"}
  ],
  deliveryDate: [
    {required: true, message: "送样日期不能为空", trigger: "blur"}
  ],
  senderPhone: [
    {required: true, message: "联系方式不能为空", trigger: "blur"}
  ],

})
let old={}

function changeSample(i){
  Object.assign(old,samples.value[i-2]);
  form.value=samples.value[i-2];
  form.value.index=i-2;
  form.value.projectId=pid;
  openChange.value=true;
}
function submitForm(){
  updates.value[form.value.index]={
    sampleName:updates.value[form.value.index].sampleName || form.value.sampleName!==old.sampleName,
    rockType:updates.value[form.value.index].rockType || form.value.rockType !==old.rockType,
    wellId:updates.value[form.value.index].wellId || form.value.wellId !==old.wellId,
    depth:updates.value[form.value.index].depth || form.value.depth !==old.depth,
    sampleQuantity:updates.value[form.value.index].sampleQuantity || form.value.sampleQuantity !==old.sampleQuantity,
    sampleSize:updates.value[form.value.index].sampleSize || form.value.sampleSize !==old.sampleSize,
    sampleBackup:updates.value[form.value.index].sampleBackup || form.value.sampleBackup !==old.sampleBackup,
    sampleSender:updates.value[form.value.index].sampleSender || form.value.sampleSender !==old.sampleSender,
    sendingStyle:updates.value[form.value.index].sendingStyle || form.value.sendingStyle !==old.sendingStyle,
    deliveryDate:updates.value[form.value.index].deliveryDate || form.value.deliveryDate !==old.deliveryDate,
    senderPhone:updates.value[form.value.index].senderPhone || form.value.senderPhone !==old.senderPhone,
    batch:updates.value[form.value.index].batch || form.value.batch !==old.batch,
    linkman:updates.value[form.value.index].linkman || form.value.linkman !==old.linkman
  }
  samples[form.value.index]=form.value;
  openChange.value=false;
}
function cancel(){
  openChange.value=false;
}

//文件更改方法
function handleChange(upload){
  let fr=new FileReader();
  fr.readAsBinaryString(upload.raw);
  fr.onload=(event)=>{
    let excel = xlsx.read(event.target.result,{type:"binary",cellDates: true});
    let sheet = excel.Sheets[excel.SheetNames[0]];
    samples.value = parse(sheet);
  }
}
//解析表格
function parse(sheet){
  if (sheet['P1'].h!='s1.0.1'){
    ElNotification({title:'导入失败',message:'请使用所给模板导入数据',type:'error'});
    return null;
  }
  let list=xlsx.utils.sheet_to_json(sheet,
      {
        header:['sampleName','rockType','wellId','depth',
          'sampleQuantity','sampleSize','sampleBackup','sampleSender',
          'sendingStyle','deliveryDate','senderPhone','batch','linkman']
      }
  )
  list = list.slice(2)
  for (let l of list) {
    if (l.sampleName==null || l.sampleQuantity==null || l.sampleSender==null
        || l.sendingStyle==null || l.deliveryDate==null || l.senderPhone==null){
      ElNotification({title:'导入失败',message:'表格必填项数据缺失',type:'error'});
      return null;
    }
    l.projectId=pid
    console.log(l.deliveryDate)
    l.deliveryDate=formattedDate(l.deliveryDate);
  }
  updates.value=[];
  for (let i = 0; i < list.length; i++) {
    updates.value[i]={
      sampleName:false,rockType:false,wellId:false,depth:false,
      sampleQuantity:false,sampleSize:false,sampleBackup:false,
      sampleSender:false, sendingStyle:false,deliveryDate:false,senderPhone:false,batch:false,linkman:false
    }
  }
  return list;
}
//控制文件数
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}
//日期格式化
function formattedDate(timestamp){
  const date = new Date(timestamp);
  //解决日期导入时间差问题
  date.setSeconds(date.getSeconds()+43);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate
}
//导入样品至数据库
function handleImport(){
  if (samples.value!=null){
    importSamples(samples.value).then(res=>{
      if (res.code==200){
        //刷新父组件列表
        emit('refresh');
        openDia.value=false;
        reset();
        ElNotification({title:'提示',message:'样品导入成功',type:"success"});
      }else {
        ElNotification({title:'导入失败',message:res.msg,type:"error"})
      }
    })
  }else {
    ElNotification({title:'导入失败',message:'未传入文件',type:"error"})
  }
}

//下载模板
function downloadTemplate(){
  let a = document.createElement('a');
  a.download = '样品导入模板.xlsx';
  a.href = '/样品导入模板.xlsx';
  a.click();
  window.URL.revokeObjectURL(a.href);
}
function reset(){
  upload.value=null;
  samples.value=[];
  updates.value=[];
}
</script>

<style scoped lang="scss">


</style>